package com.hj.service;

import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.Auditable;

public class EntityListener implements InitializingBean {
	private Logger log = LogManager.getLogger(getClass());
	private static final String UPDATOR = "lastModifiedBy";
	private static final String UPDATEDDATE = "lastModifiedDate";
	private static final String CREATOR = "createdBy";
	private static final String CREATEDDATE = "createdDate";

	@PrePersist
	public void touchForCreate(Object entity) throws Throwable {
		Date now = new Date();
		String userCd = SpringSecurityUtils.getCurrentUserName();
		// 如果当然登录用户用空，取Admin
		if (StringUtils.isEmpty(userCd)) {
			userCd = "admin";
		}
		// 创建时间
		Date createdDate = (Date) PropertyUtils.getProperty(entity, CREATEDDATE);
		if (createdDate == null) {
			BeanUtils.setProperty(entity, CREATEDDATE, now);
		}
		// 创建人
		String creator = (String) PropertyUtils.getProperty(entity, CREATOR);
		if (StringUtils.isEmpty(creator)) {
			BeanUtils.setProperty(entity, CREATOR, userCd);
		}
	}

	/**
	 * Sets modification and creation date and auditor on the target object in case it implements {@link Auditable} on
	 * update events.
	 * 
	 * @param target
	 */
	@PreUpdate
	public void touchForUpdate(Object entity) throws Throwable {
		log.info(entity);
		Date now = new Date();
		String userCd = SpringSecurityUtils.getCurrentUserName();
		// 如果当然登录用户用空，取Admin
		if (StringUtils.isEmpty(userCd)) {
			userCd = "admin";
		}
		 // 更新时间
		BeanUtils.setProperty(entity, UPDATEDDATE, now);
		// 更新人
		BeanUtils.setProperty(entity, UPDATOR, userCd);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub

	}

}
